function numIslands(grid: string[][]): number {
  let ans = 0;
  const l = grid.length;
  const r = grid[0].length;
  const visited: boolean[][] = new Array(l).fill(null).map(() => new Array(r).fill(false));
  for (let y = 0; y < l; y++) {
    for (let x = 0; x < r; x++) {
      if (grid[y][x] === '1' && !visited[y][x]) {
        ans++;
        bfs(x, y);
      }
    }
  }
  return ans;
  function bfs(x: number, y: number) {
    const dir = [[0, -1], [1, 0], [0, 1], [-1, 0]];
    const q: [number, number][] = [];
    q.push([x, y]);
    visited[y][x] = true;
    while (q.length) {
      const item = q.shift();
      const x = item[0];
      const y = item[1];
      for (let d = 0; d < 4; d++) {
        const nx = x + dir[d][0];
        const ny = y + dir[d][1];
        if (nx < 0 || nx >= r || ny < 0 || ny >= l) continue;
        if (grid[ny][nx] !== '1') continue;
        if (visited[ny][nx]) continue;
        q.push([nx, ny]);
        visited[ny][nx] = true;
      }
    }
  }
};